import { NextRequest, NextResponse } from 'next/server';
import { getDeviceParameterDb } from '@/lib/device-parameter-database';

export interface DeviceClassification {
  classification_name: string;
  classification_code: string;
  specialty: string;
  device_count: number;
  naming_table?: string;
  position_table?: string;
  base_params_table?: string;
  naming_table_display?: string;
  position_table_display?: string;
  base_params_table_display?: string;
}

// GET /api/device-classifications?specialty=配管专业
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const specialty = searchParams.get('specialty');
    
    const db = getDeviceParameterDb();
    
    // 从devices表获取设备分类统计
    let query = `
      SELECT 
        classification_name,
        classification_code,
        specialty,
        COUNT(*) as device_count
      FROM devices 
      WHERE classification_name IS NOT NULL 
        AND classification_name != ''
    `;
    
    const params: any[] = [];
    
    if (specialty) {
      query += ' AND specialty = ?';
      params.push(specialty);
    }
    
    query += `
      GROUP BY classification_name, classification_code, specialty
      ORDER BY classification_name
    `;
    
    const deviceParameterDb = db as any;
    const stmt = deviceParameterDb.db.prepare(query);
    const classifications = stmt.all(...params) as DeviceClassification[];
    
    // 为每个分类获取表映射信息
    const classificationsWithMapping = classifications.map(classification => {
      // 尝试从device_type_mappings获取表映射信息
      const mapping = db.getDeviceTypeMapping(classification.classification_code);
      
      if (mapping) {
        return {
          ...classification,
          naming_table: mapping.naming_table,
          position_table: mapping.position_table,
          base_params_table: mapping.base_params_table,
          naming_table_display: extractTableCode(mapping.naming_table),
          position_table_display: extractTableCode(mapping.position_table),
          base_params_table_display: extractTableCode(mapping.base_params_table)
        };
      }
      
      return classification;
    });
    
    return NextResponse.json({
      success: true,
      data: classificationsWithMapping
    });
    
  } catch (error) {
    console.error('获取设备分类失败:', error);
    return NextResponse.json({
      success: false,
      error: error instanceof Error ? error.message : '获取设备分类失败'
    }, { status: 500 });
  }
}

// 从表名提取显示代码，如 "table_c2" -> "C.2"
function extractTableCode(tableName: string): string {
  if (!tableName) return '';
  const match = tableName.match(/table_c(\d+)/i);
  return match ? `C.${match[1]}` : tableName;
}